﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Collections;
using System.IO;
using System.Diagnostics;

namespace Collector
{
    public delegate void ShowMessage_Delegate(string Msg);
    public class FileConfig
    {
        public class Common
        {
            public int DutNumber = 4;
            public string CommonConfigPath = Application.StartupPath + "\\Setting.config";
            public string strLogDir = "";
            public bool bLockTestMode = false;
            //public PortType testPorttype;
            public int iSelectedTestmode = 0;
            public int RunningCycleCount = 0;
            public int DebugPulseData = 0;
            // 允许保存有效的脉压采集数据
            public int AllowSavePulseData = 0;
            //Server
            public  bool connectServer = false;
            public CheckCanGoMode CanGoMode = CheckCanGoMode.WTMES;
            //UploadLog
            public  bool UploadLogEnable = false;
            public  string UploadIpaddress = "";
            public  string UploadUser = "";
            public  string UploadPwd = "";
            public string uploaderRemoteFolder = "";
            //SN Setting
            //public bool InPutSN = false;        
            public bool bTmobileLogEnable=false;
            public string bTmobileLogName = "WT";

            public Dictionary<string, string> dictCommonMap = new Dictionary<string, string>();

        }
        public class TestModeInfo
        {
            //public bool bEnable;
            public string mode;

        }
        public class TestItemInfo
        {
            public bool bEnable;
            public string itemName;
            public Dictionary<string, string> dictParams = new Dictionary<string, string>();
        }
        public class ThresholdValueInfo
        {
            public string itemValue;
            public string itemName;
            public Dictionary<string, string> dictLowUPValues = new Dictionary<string, string>();
        }
        public class SerialPortDataInfo
        {
            public string itemValue;
            public string itemName;
            public Dictionary<string, string> dicSerialPortData = new Dictionary<string, string>();
        }
        public class GroupInfo
        {
            public bool bEnable;
            public int iDutPortQloader;
            public int iDutPort90B8;
            public string strLoction;

        }
        public enum CheckCanGoMode
        {
            WTMES,
            APOLLO,
            WTDegrade,

            CM_Max
        }
        public class ControlPlus
        {
            public string value = "";
            public bool Visible = false;
            public string regx = "";
            public string label = "";
            public string FileExtension = "";
        }

        public class DloadModeInfo
        {
            public string Name = "";
            //public string ClassName = "";
            public bool enable = true;
            //public ViewPlus SnSetting = new ViewPlus();
            public ControlPlus Programmer = new ControlPlus();
            public ControlPlus SearchPath = new ControlPlus();
            public ControlPlus rawprogramXml = new ControlPlus();
            public ArrayList rawprogramXmlList = new ArrayList();
            public ControlPlus pathXml = new ControlPlus();
            public ArrayList pathXmlList = new ArrayList();
            public ControlPlus memoryFlashType = new ControlPlus();
            
            public string DownloadPortName;
            public string NormalPortName;
            //public bool InputSN()
            //{
            //    return SnSetting.Visible && (SnSetting.value > 0);
            //}
        }
        public class FixControlInfo
        {
            public bool enable;
            public int[] FixPort = new int[Max_Dut_Count];
        }
        public static int Max_Dut_Count = 8;
        public static Common CommonParam = new Common();
        public static GroupInfo[] GroupParam = null;//new GroupInfo[Max_Dut_Count];
        public static TestItemInfo testItem_Info = new TestItemInfo();
        public static ThresholdValueInfo thresholdValue_Info = new ThresholdValueInfo();
        public static SerialPortDataInfo serialPortData_Info = new SerialPortDataInfo();
        public static FixControlInfo fixInfo = new FixControlInfo();
        public static TestModeInfo[] testMode_Info =null;// new TestModeInfo[Max_Dut_Count];
        //public static List<DloadModeInfo> TestModeInfo = new List<DloadModeInfo>();
        //public static List<DloadModeInfo> TestItemInfo = new List<DloadModeInfo>();
        public static string SwVersionFromMes = "";
        public static object locker = new object();
        public static string PartNumberFromMes = "";   //N21项目，有100K机器需要改NV，需要读取PartNumber来确认是否需要改。
        public static string HTC_PCB_Version = "";  //HTC客户定制信息写入
        public static string HTC_PCB_ID_Field = "";  //HTC客户定制信息写入
        //public static string LGModelName = "";   //LG 项目，在线升级需要增加model name作为参数
        //public static DloadModeInfo GetTestModeInfo()
        //{
        //    return FileConfig.TestModeInfo[CommonParam.iSelectedTestmode];
        //}

        public static bool ReadCommonConfig(string ConfigFilePath)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(ConfigFilePath);
                XmlNodeList list = xmlDoc.DocumentElement.ChildNodes;
                foreach (XmlNode Node in list)
                {
                    if (Node.Name == "Common")
                    {
                        CommonParam.dictCommonMap.Clear();
                        XmlNodeList listCommon = Node.ChildNodes;
                        foreach (XmlNode commonNode in listCommon)
                        {
                            if (commonNode.Name == "UploadLog")
                            {
                                CommonParam.dictCommonMap[commonNode.Name] = commonNode.Attributes["Enable"].Value;
                                CommonParam.UploadLogEnable = (commonNode.Attributes["Enable"].Value == "1");
                                CommonParam.UploadIpaddress = commonNode.Attributes["address"].Value;
                                CommonParam.UploadUser = commonNode.Attributes["User"].Value;
                                CommonParam.UploadPwd = commonNode.Attributes["Password"].Value;
                                CommonParam.uploaderRemoteFolder = commonNode.Attributes["remoteDir"].Value;
                            }

                            if (commonNode.Name == "LockTestMode")
                            {
                                CommonParam.dictCommonMap[commonNode.Name] = commonNode.Attributes["Enable"].Value;
                                CommonParam.bLockTestMode= (commonNode.Attributes["Enable"].Value == "1");
                            }
                            if (commonNode.Name == "TestMode")
                            {
                                CommonParam.dictCommonMap[commonNode.Name] = commonNode.Attributes["value"].Value;
                                CommonParam.iSelectedTestmode = Convert.ToInt32(commonNode.Attributes["value"].Value);
                            }
                            if (commonNode.Name == "RunningCycleCount")
                            {
                                CommonParam.dictCommonMap[commonNode.Name] = commonNode.Attributes["value"].Value;
                                CommonParam.RunningCycleCount = Convert.ToInt32(commonNode.Attributes["value"].Value);
                            }
                            if (commonNode.Name == "DebugPulseData")
                            {
                                CommonParam.dictCommonMap[commonNode.Name] = commonNode.Attributes["value"].Value;
                                CommonParam.DebugPulseData = Convert.ToInt32(commonNode.Attributes["value"].Value);
                            }
                            if (commonNode.Name == "AllowSavePulseData")
                            {
                                CommonParam.dictCommonMap[commonNode.Name] = commonNode.Attributes["value"].Value;
                                CommonParam.AllowSavePulseData = Convert.ToInt32(commonNode.Attributes["value"].Value);
                                Log.Debug("AllowSavePulseData={0}, value={1}", CommonParam.AllowSavePulseData, commonNode.Attributes["value"].Value);
                            }
                        }
                    }
                    if (Node.Name == "TestItemCfg")
                    {
                        XmlNodeList listTestMode = Node.ChildNodes;
                        foreach (XmlNode GroupNode in listTestMode)
                        {
                            if (GroupNode.Name == "Params")
                            {
                                XmlNodeList xmllist = GroupNode.ChildNodes;
                                testItem_Info.dictParams.Clear();
                                foreach (XmlNode xmlNode in xmllist)
                                {
                                    if ("#comment" == xmlNode.Name)
                                    {
                                        continue;
                                    }
                                    string key = xmlNode.Attributes["name"].Value;
                                    string value = xmlNode.Attributes["value"].Value;
                                    testItem_Info.dictParams[key] = value;
                                }
                            }
                        }
                    }
                    if (Node.Name == "ThresholdValue")
                    {
                        XmlNodeList listTestMode = Node.ChildNodes;
                        foreach (XmlNode GroupNode in listTestMode)
                        {
                            if (GroupNode.Name == "Params")
                            {
                                XmlNodeList xmllist = GroupNode.ChildNodes;
                                thresholdValue_Info.dictLowUPValues.Clear();
                                foreach (XmlNode xmlNode in xmllist)
                                {
                                    if ("#comment" == xmlNode.Name)
                                    {
                                        continue;
                                    }
                                    string key = xmlNode.Attributes["name"].Value;
                                    string value = xmlNode.Attributes["value"].Value;
                                    thresholdValue_Info.dictLowUPValues[key] = value;
                                }
                            }
                        }
                    }
                    if (Node.Name == "SerialPortData")
                    {
                        XmlNodeList listTestMode = Node.ChildNodes;
                        foreach (XmlNode GroupNode in listTestMode)
                        {
                            if (GroupNode.Name == "Params")
                            {
                                XmlNodeList xmllist = GroupNode.ChildNodes;
                                serialPortData_Info.dicSerialPortData.Clear();
                                foreach (XmlNode xmlNode in xmllist)
                                {
                                    if ("#comment" == xmlNode.Name)
                                    {
                                        continue;
                                    }
                                    string key = xmlNode.Attributes["name"].Value;
                                    string value = xmlNode.Attributes["value"].Value;
                                    serialPortData_Info.dicSerialPortData[key] = value;
                                }
                            }
                        }
                    }
                    if (Node.Name == "GroupSetting")
                    {
                        XmlNodeList listTestMode = Node.ChildNodes;
                        GroupParam = new GroupInfo[listTestMode.Count];
                        foreach (XmlNode GroupNode in listTestMode)
                        {
                            int index = Convert.ToInt32(GroupNode.Attributes["index"].Value);
                            GroupParam[index] = new GroupInfo();
                            GroupParam[index].bEnable = Convert.ToInt32(GroupNode.Attributes["enable"].Value) > 0;
                            GroupParam[index].iDutPortQloader = Convert.ToInt32(GroupNode.Attributes["comportQloader"].Value);
                            GroupParam[index].iDutPort90B8 = Convert.ToInt32(GroupNode.Attributes["comport90B8"].Value);
                            GroupParam[index].strLoction = GroupNode.Attributes["location"].Value;
                        }
                    }
                    if (Node.Name == "TestModeCfg")
                    {
                        XmlNodeList listTestMode = Node.ChildNodes;
                        testMode_Info = new TestModeInfo[listTestMode.Count];
                        foreach (XmlNode ItemModeNode in listTestMode)
                        {
                            int index = Convert.ToInt32(ItemModeNode.Attributes["index"].Value);
                            testMode_Info[index] = new TestModeInfo();
                            testMode_Info[index].mode = ItemModeNode.Attributes["mode"].Value;
                            //testMode_Info[index].bEnable = Convert.ToInt32(ItemModeNode.Attributes["enable"].Value) > 0;
                        }

                    }
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show("ReadCommonConfig :"+exp.Message);
                return false;
            }
            return true;
        }
        public static bool SaveCommonConfig(string ConfigFilePath)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(ConfigFilePath);
                XmlNodeList list = xmlDoc.DocumentElement.ChildNodes;

                foreach (XmlNode Node in list)
                {
                    if (Node.Name == "Common")
                    {
        
                        Node.RemoveAll();
                        foreach (KeyValuePair<string, string> kv in CommonParam.dictCommonMap)
                        {
                            XmlElement pairXml = xmlDoc.CreateElement("element", kv.Key, "");
                            string value = null;
                            if(kv.Key == "UploadLog")
                            {                                
                                pairXml.SetAttribute("Enable", CommonParam.UploadLogEnable ? "1" : "0");
                                pairXml.SetAttribute("address", CommonParam.UploadIpaddress);
                                pairXml.SetAttribute("User", CommonParam.UploadUser);
                                pairXml.SetAttribute("Password", CommonParam.UploadPwd);
                                pairXml.SetAttribute("remoteDir", CommonParam.uploaderRemoteFolder);
                                Node.AppendChild(pairXml);
                            }
                            else if(kv.Key == "LockTestMode")
                            {
                                pairXml.SetAttribute("Enable", CommonParam.bLockTestMode ? "1" : "0");
                                Node.AppendChild(pairXml);
                            } 
                            else if(kv.Key == "TestMode")
                            {
                                if(CommonParam.iSelectedTestmode == 0)
                                {
                                    value = "0";
                                } else if (CommonParam.iSelectedTestmode == 1)
                                {
                                    value = "1";
                                } else if (CommonParam.iSelectedTestmode == 2)
                                {
                                    value = "2";
                                }
                                else if (CommonParam.iSelectedTestmode == 3)
                                {
                                    value = "3";
                                }
                                else if(CommonParam.iSelectedTestmode == 4)
                                {
                                    value = "4";
                                }
                            } else if(kv.Key == "DebugPulseData")
                            {
                                value = (CommonParam.DebugPulseData == 1) ? "1" : "0";
                            }
                            else if(kv.Key == "AllowSavePulseData")
                            {
                                value = (CommonParam.AllowSavePulseData == 1) ? "1" : "0";
                            }

                            if(value != null)
                            {
                                pairXml.SetAttribute("value", value);

                                Node.AppendChild(pairXml);
                            }

                        }
                    }
                    if (Node.Name == "GroupSetting")
                    {
                        Node.RemoveAll();
                        for (int i = 0; i < FileConfig.GroupParam.GetLength(0); i++)
                        {
                            XmlElement child = xmlDoc.CreateElement("element", "DUT", "");
                            child.SetAttribute("index", String.Format("{0}", i));
                            child.SetAttribute("enable", FileConfig.GroupParam[i].bEnable ? "1" : "0");
                            child.SetAttribute("comportQloader", FileConfig.GroupParam[i].iDutPortQloader.ToString());
                            child.SetAttribute("comport90B8", FileConfig.GroupParam[i].iDutPort90B8.ToString());
                            child.SetAttribute("location", FileConfig.GroupParam[i].strLoction);
                            Node.AppendChild(child);
                        }
                    }
                    if (Node.Name == "TestItemCfg")
                    {
                        Node.RemoveAll();
                        XmlElement child = xmlDoc.CreateElement("element", "Params", "");
                        foreach (KeyValuePair<string, string> kv in testItem_Info.dictParams)
                        {
                            XmlElement pairXml = xmlDoc.CreateElement("element", "key", "");
                            pairXml.SetAttribute("name", kv.Key);
                            pairXml.SetAttribute("value", kv.Value);

                            child.AppendChild(pairXml);
                        }
                        Node.AppendChild(child);
                    }
                    if (Node.Name == "ThresholdValue")
                    {
                        Node.RemoveAll();
                        XmlElement child = xmlDoc.CreateElement("element", "Params", "");
                        foreach (KeyValuePair<string, string> kv in thresholdValue_Info.dictLowUPValues)
                        {
                            XmlElement pairXml = xmlDoc.CreateElement("element", "key", "");
                            pairXml.SetAttribute("name", kv.Key);
                            pairXml.SetAttribute("value", kv.Value);

                            child.AppendChild(pairXml);
                        }
                        Node.AppendChild(child);
                    }
                    if (Node.Name == "TestModeCfg")
                    {
                        Node.RemoveAll();
                        for (int i = 0; i < FileConfig.testMode_Info.GetLength(0); i++)
                        {
                            XmlElement child = xmlDoc.CreateElement("element", "TestMode", "");
                            child.SetAttribute("index", String.Format("{0}", i));
                            //child.SetAttribute("enable", FileConfig.testMode_Info[i].bEnable ? "1" : "0");
                            child.SetAttribute("mode", FileConfig.testMode_Info[i].mode);
                            Node.AppendChild(child);
                        }
                    }
                }
                xmlDoc.Save(ConfigFilePath);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
                return false;
            }
            return true;
        }

        public static double ReadThresholdValue(string key)
        {
            return GetThresholdValue(key, "0");
        }

        public static bool WritePCBSN()
        {
            bool benable = false;
            if (!GetParamValue("WritePCBSN", out benable, "0"))
            {
                return false;
            }
            return benable;
        }
        public static bool WriteFixedFrequency()
        {
            bool benable = false;
            if (!GetParamValue("WriteFixedFrequency", out benable, "0"))
            {
                return false;
            }
            return benable;
        }
        public static bool AirResetTest()
        {
            bool benable = false;
            if (!GetParamValue("AirResetTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }
        //PulseSFTTest
        public static bool PulseSFTTest()
        {
            bool benable = false;
            if (!GetParamValue("PulseSFTTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }
        public static bool PulseFFTTest()
        {
            bool benable = false;
            if (!GetParamValue("PulseFFTTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }
        //连续加压-连续模式
        public static bool PulseConsecutiveTest()
        {
            bool benable = false;
            if (!GetParamValue("PulseConsecutiveTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }
        // 三部-分段模式
        public static bool PulseThreeBodyTest_Subsection()
        {
            bool benable = false;
            if (!GetParamValue("PulseThreeBodyTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }

        // 三部-连续模式
        public static bool PulseThreeBodyTest_Continuous()
        {
            bool benable = false;
            if (!GetParamValue("PulseThreeBodyContinuousTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }

        // 检查是否是三部采脉。包含三部分段或三部连续
        public static bool PulseThreeBodyTest()
        {
            if (PulseThreeBodyTest_Subsection() || PulseThreeBodyTest_Continuous())
                return true;

            return false;
        }
        //分段加压
        public static bool PulseSubsectionTest()
        {
            bool benable = false;
            if (!GetParamValue("PulseSubsectionTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }
        public static bool PulseFixtureTest()
        {
            bool benable = false;
            if (!GetParamValue("FixtureTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }
        public static string getmmHgList(string key)
        {
            return testItem_Info.dictParams[key.Trim()];
        }

        public static bool getmmHgListInfo(string key, out string mmHgList)
        {
            mmHgList = "";
            if (null == testItem_Info.dictParams)
                return false;

            if (!testItem_Info.dictParams.ContainsKey(key.Trim()))
            {
                return false;
            }
            else
            {
                mmHgList = testItem_Info.dictParams[key.Trim()];
            }

            return true;
        }
        public static bool LedTest()
        {
            bool benable = false;
            if (!GetParamValue("LedTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }

        public static bool AgingTest()
        {
            bool benable = false;
            if (!GetParamValue("AgingTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }

        public static bool PulsePressureTest()
        {
            bool benable = false;
            if (!GetParamValue("PulsePressureTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }
        public static bool AirPressureTest()
        {
            bool benable = false;
            if (!GetParamValue("AirPressureTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }
        public static bool RunningTest()
        {
            bool benable = false;
            if (!GetParamValue("RunningTest", out benable, "0"))
            {
                return false;
            }
            return benable;
        }

        public static bool GetParamValue(string key, out bool bEnable, string strdefault = "", string spliter = ",")
        {
            bEnable = false;
            if (null == testItem_Info.dictParams)
            {
                return false;
            }

            string value = "";
            if (!testItem_Info.dictParams.ContainsKey(key.Trim()))
            {
                if (strdefault.Trim().Length <= 0)
                {
                    return false;
                }
                value = strdefault;
            }
            else
            {
                value = testItem_Info.dictParams[key.Trim()];
            }

            //string[] sArray = value.Trim().Split(new string[] { spliter }, StringSplitOptions.RemoveEmptyEntries);
            //if (sArray.Length < 1)
            //{
            //    return false;
            //}
            bEnable = Convert.ToInt32(value) > 0;

            return true;
        }
        public static double GetThresholdValue(string key, string strdefault = "", string spliter = ",")
        {
            string value = "";
            if (! thresholdValue_Info.dictLowUPValues.ContainsKey(key.Trim()))
            {
                if (strdefault.Trim().Length <= 0)
                {
                    return -100;
                }
            }
            else
            {
                value = thresholdValue_Info.dictLowUPValues[key.Trim()];
            }
            return Convert.ToDouble(value);
        }
        public static int GetConfigValueToInt(string key, string strdefault = "", string spliter = ",")
        {
            string value = "";
            if (!thresholdValue_Info.dictLowUPValues.ContainsKey(key.Trim()))
            {
                if (strdefault.Trim().Length <= 0)
                {
                    return -100;
                }
            }
            else
            {
                value = thresholdValue_Info.dictLowUPValues[key.Trim()];
            }
            return Convert.ToInt32(value);
        }
        public static byte[] getSerialPortData(string key)
        {
            string headMsg = "";
            ArrayList alSPData = new ArrayList();
            headMsg = serialPortData_Info.dicSerialPortData[key.Trim()];
            //Log.Debug("headMsg :" + headMsg);
            string[] headArray = headMsg.Split(',');
            for (int i = 0; i < headArray.Length; i++)
            {
                alSPData.Add(Convert.ToByte(headArray[i].Trim(), 16));
            }
            return (byte[])alSPData.ToArray(typeof(byte));
        }

    }
}
